const staticPath = "web/";
const _mp = require('./web/mp/config/mp');
const fs = require('fs');
const { src, dest, watch, series, parallel, task } = require("gulp");
const babel = require("gulp-babel");
const uglify = require("gulp-uglify");
const rename = require("gulp-rename");
const concat = require("gulp-concat");
const browserify = require("gulp-browserify");
const gulpHtmlVersion = require("gulp-html-version");
const spritesmith = require("gulp.spritesmith");
const minimist = require("minimist");
const js_obfuscator = require('gulp-js-obfuscator');
const replace = require("gulp-replace");
const jeditor = require("gulp-json-editor");
const QRCode = require('qrcode');
const htmlmin = require('gulp-htmlmin');

const gaokaoPath = staticPath + "mp/";
const pcPath = staticPath + "pc/";
const buildPath = '../gaokao-mp/'
const distPath = './dist/'
const timestamp = parseInt(new Date().getTime() / 1000);
const run = require('gulp-run');
var ico = require('gulp-to-ico');
let options = minimist(process.argv.slice(2));
let envStr = options.env || undefined;
let { plus, ver, env } = minimist(process.argv);
plus = plus ? plus : 0;
console.log("gulp env", envStr, typeof envStr, options);
function fileLoad(){
	// console.log("process.env.NODE_ENV",env, ver, plus );
	return src(gaokaoPath + 'env.js').pipe(replace(/currentVersion\s=\s\'[a-z]*\'/g, function(match,p1,offset,string){
		let str = match.slice(0, match.indexOf("'"))
		return str + "'" + env + "'";
	}))
	.pipe(replace(/environment\s=\s\'[a-z]*\'/g, function(match,p1,offset,string){
		let str = match.slice(0, match.indexOf("'"))
		return str + "'release'";
	}))
	.pipe(replace(/version\s=\s[0-9]*/g, function(match,p1,offset,string){
		let str = match.slice(0, match.indexOf("=") + 1)
		let version = ver && typeof ver == "object"  ? ver[1] : ver
		return str + " " + (version || 1) ;
	})).pipe(dest(buildPath + 'common/'))
}

function copy(){
	let path = staticPath + `plus/${plus}/manifest.json`;
	return src(path).pipe(dest('dist/'))
}
function jsonConvert(){
	let path = gaokaoPath + `manifest.json`;
	console.log('plus', plus , _mp[env])
	return src(path).pipe(jeditor(function(json){
		if(_mp[env]) {
			json['mp-weixin'].appid = _mp[env].appid;
		}
		if(!plus) {
			json['mp-weixin'].uniStatistics = {
				"enable" : false
			};
			json['mp-weixin'].plugins = {};
		}
		return json
	}))
	.pipe(dest(buildPath))
}
function shellRun() {
	let cmd = `cd ../gaokao-mp && cd && `;
	let commontShell = ' && git pull && git status';
	// let env = options['_'];
	if(env == 'lizy') {
		cmd += `git checkout Release` + commontShell
	} else if(env == 'yuanzy') {
		cmd += `git checkout YUANZY-Release` + commontShell
	} else if(env == 'zywang') {
		cmd += `git checkout Release-OEM-zywang` + commontShell
	} else if(env == 'chuangjingzy') {
		cmd += `git checkout Release-OEM-chuangjingzy` + commontShell
	} else if(env == 'huigaokao') {
		cmd += `git checkout Release-OEM-huigaokao` + commontShell
	} else if(env == 'farcoach') {
		cmd += `git checkout FARCOACH-Release` + commontShell
	} else if(env == 'ddsx') {
		cmd += `git checkout Release-OEM-ddsx` + commontShell
	} else if(env == 'zwzyt') {
		cmd += `git checkout Release-OEM-zwzyt` + commontShell
	} else if(env == 'bangzy') {
		cmd += `git checkout Release-OEM-bangzy` + commontShell
	} else if(env == 'test') {
		cmd += `git pull && git status`
	} else {
		cmd += `git checkout Release-OEM-${env}` + commontShell
	}
	console.log('cmd', cmd)
	return run(cmd).exec()
}
function setTitle() {
	console.log("process.env.NODE_ENV",env );
	let title = env ? env : '';
	return src(pcPath+'*').pipe(replace(/{{title}}/g, function(match,p1,offset,string){
		let str = match.slice(0, match.indexOf("'"))
		return title;
	}))
	.pipe(dest(distPath))
}

function fileName(){
	return src('dist/new_file -*', {
		resolveSymlinks : function(vl) {
			conosole.log(vl)
		}
	}).pipe(rename(function(path){
		let name = path.basename;
		if(name.includes('- 副本')) {
			let str = name.split('-');
			console.log(str[0].trim()+"_"+ parseInt( Math.random()*1000))
			path.basename = str[0].trim()+"_"+ parseInt( Math.random()*1000)
		}
	})).pipe(dest('dist/file'))
}
function moveFile(){
	return src('dist/file/*').pipe(dest('dist/'))
}
// 图片转ico, gulp fav --env ico.png
function favicon() {
	let name = env;
	let path = "web/image/ico/";
	if(name) {
		path += name
	} else {
		path += 'ico.png'
	}
	console.log('favicon', name, path)
  return src(path)
	.pipe(ico('favicon.ico', { resize: true, sizes: [16, 24, 32] }))
	.pipe(dest('./dist/ico'));
}
// 二维生成
// 志愿卡激活,口令激活二维码生成
function getVipEncode() {
	let domain = env||''; //不含https
	let qrcodeUrl = "https://www.lzy-gaokao.com/qrcode.php?size=6&value=";
	let str1 =`https://${domain}/?uri=/pages/topic/activation/activate-code`;//口令激活
	let str2 =`https://${domain}/card`;//志愿卡激活
	let outPath = distPath+'qr/';
	const opts = {
		errorCorrectionLevel: 'M',
		type: 'image/png',
		quality: 1,
		margin: 2,
		width: 300,
		height: 300
	};
	const getQrcode = (str, name="qrcode") => (
		QRCode.toDataURL(str, opts)
		  .then(url => {
				url = url.split('base64,')[1]
				let buffer = Buffer.from(url, 'base64');
				// 写入文件到系统
				fs.writeFile(outPath+name+'.png', buffer, { encoding: 'base64' }, function(err) {
				if (err) {
				console.log(err);
				} else {
					console.log(name+'文件保存成功', str);
					return false;
				}
			});
		  })
		  .catch(err => {
			console.error(err);
		  })
	)
	
	if(domain) {
		getQrcode(str1,'口令激活');
		getQrcode(str2,'志愿卡激活');
	} else {
		console.warn('env必须配置域名，不含https')
		return false;
	}
}

function fileLoadTest() {
		// console.log("process.env.NODE_ENV",env, ver, plus );
	return src(gaokaoPath + 'env.js').pipe(replace(/currentVersion\s=\s\'[a-z]*\'/g, function(match,p1,offset,string){
		let str = match.slice(0, match.indexOf("'"))
		return str + "'lizy'";
	}))
	.pipe(replace(/environment\s=\s\'[a-z]*\'/g, function(match,p1,offset,string){
		let str = match.slice(0, match.indexOf("'"))
		console.log('--str', str)
		return str + "'test'";
	}))
	.pipe(replace(/version\s=\s[0-9]*/g, function(match,p1,offset,string){
		let str = match.slice(0, match.indexOf("=") + 1)
		let version = ver && typeof ver == "object"  ? ver[1] : ver
		return str + " " + (version || 1) ;
	})).pipe(dest(buildPath + 'common/'))
}
function jsonConvertTest(){
	let path = gaokaoPath + `manifest.json`;
	console.log('plus', plus , _mp[env])
	return src(path).pipe(jeditor(function(json){
		if(_mp[env]) {
			json['mp-weixin'].appid = _mp[env].appid;
		}
		return json
	}))
	.pipe(dest(buildPath))
}
//hotfix拉取代码: 
// gulp gaokaoWeb --env common 
// gulp gaokaoWeb --env hotfix  
// gulp gaokaoWeb --env lizy
// gulp gaokaoWeb --env hotfix,lizy,yuanzy
//项目程序， 'lizy','yuanzy', ‘zywang’,'ddsx','zwzyt',‘bangzy'','dingzy','yuanzyai',farcoach
//gulp gaokaoWeb --env hotfix,lizy,yuanzy,zywang,ddsx,zwzyt,bangzy,dingzy,yuanzyai,oem
//gulp gaokaoWeb --env zywang,ddsx,zwzyt,bangzy,dingzy,yuanzyai,oem
//OEM特殊模式 1: oem , 2'chuangjingzy','huigaokao' , 
//1、 gulp gaokaoWeb --env oem
//2、 gulp gaokaoWeb --env huigaokao,chuangjingzy
function gaokaoWebMerge() {
	let cmd = `cd ../gaokao_web && cd && git pull && `;
	let shellOpts = {
		'hotfixShell' : `git checkout Hotfix-4-release && git pull && git status`, //hotfix拉取代码
		'commonShell' : `git checkout Hotfix-4-release && git pull  && git status  && git merge Hotfix-caish  && git status && git push`,
		// OEM特殊模式
		'oemShell' : `git checkout OEM-Release && git pull  && git status  && git merge Hotfix-4-release  && git status && git push`,
		'huigaokaoShell' : `git checkout HUIGK-OEM-Release && git pull  && git status  && git merge OEM-Release  && git status && git push`,
		'chuangjingzyShell' : `git checkout CJZY-OEM-Release && git pull  && git status  && git merge OEM-Release  && git status && git push`,
		// 立志愿
		'hotfixLizyShell' : `git checkout Hotfix-4-release-lizy && git pull && git status  && git merge Hotfix-4-release  && git status && git push`,
		// 'lizyShell' : `git checkout Release && git pull  && git status && git merge Hotfix-4-release-lizy  && git status && git push`,
		'lizyShell' : `git checkout Release && git pull  && git status && git merge Hotfix-4-release  && git status && git push`,
		// 通用模式
		'yuanzyShell' : `git checkout YUANZY-Release && git pull  && git status  && git merge Hotfix-4-release  && git status && git push`,
		'zywangShell' : `git checkout ZYW-OEM-Release && git pull  && git status  && git merge Hotfix-4-release  && git status && git push`,
		'farcoachShell' : `git checkout FARCOACH-Release && git pull  && git status  && git merge Hotfix-4-release  && git status && git push`,
		'ddsxShell' : `git checkout DDSX-OEM-Release && git pull  && git status  && git merge Hotfix-4-release  && git status && git push`,
		'zwzytShell' : `git checkout ZWZYT-OEM-Release && git pull  && git status  && git merge Hotfix-4-release  && git status && git push`,
		'bangzyShell' : `git checkout BANG-Release && git pull  && git status  && git merge Hotfix-4-release  && git status && git push`,
		'dingzyShell' : `git checkout DING-Release && git pull  && git status  && git merge Hotfix-4-release  && git status && git push`,
		'yuanzyaiShell' : `git checkout YUAN-OEM-Release && git pull  && git status  && git merge Hotfix-4-release  && git status && git push`,
	}
	let allArr = ['hotfix','lizy','yuanzy', 'zywang','ddsx','zwzyt','bangzy','dingzy','yuanzyai','oem','huigaokao','chuangjingzy'];
	let arr = env.includes(',') ? env.split(',') : env.split(' ')
	if(arr.length > 1) {
		for(let key of arr) {
			cmd += shellOpts[key+'Shell'] + ' && ';
		}
		cmd = cmd.slice(0, cmd.length-3)
	} else {
		if(arr[0] === 'all' || arr[0] === '*') {
			for(let key of allArr) {
				cmd += shellOpts[key+'Shell'] + ' && ';
			}
			cmd = cmd.slice(0, cmd.length-3)
		} else {
			cmd += shellOpts[arr[0]+'Shell'];
		}
	}
	console.log('**************** cmd ********************')
	console.log(env,arr)
	console.log(cmd)
	console.log('**************** cmd end ****************')
	return run(cmd).exec()
}
//hotfix拉取代码: 'lizy','yuanzy', ‘zywang’,'ddsx','zwzyt',‘bangzy'','dingzy','yuanzyai',oem
//0: gulp gaokaoMp --env common  
//1: gulp gaokaoMp --env hotfix  
//2: gulp gaokaoMp --env lizy,yuanzy
//3: gulp gaokaoMp --env zywang,zwzyt,
//3: gulp gaokaoMp --env ddsx,bangzy,oem
//3: gulp gaokaoMp --env dingzy,yuanzyai,oem
//OEM特殊模式 1: oem , 2'chuangjingzy','huigaokao' , 
//4:  gulp gaokaoMp --env huigaokao,chuangjingzy
function gaokaoMpMerge() {
	let cmd = `cd ../gaokao-mp && cd && git pull && `;
	let shellOpts = {
		'commonShell' : `git checkout Hotfix-4-release && git pull  && git status  && git merge Hotfix-caish  && git status && git push`,
		'hotfixShell' : `git checkout Hotfix-4-release && git pull  && git status`,
		// OEM特殊模式
		'oemShell' : `git checkout Release-OEM && git pull  && git status  && git merge Hotfix-4-release  && git status && git push`,
		'huigaokaoShell' : `git checkout Release-OEM-huigaokao && git pull  && git status  && git merge Release-OEM  && git status && git push`,
		'chuangjingzyShell' : `git checkout Release-OEM-chuangjingzy && git pull  && git status  && git merge Release-OEM  && git status && git push`,
		// 立志愿
		// 'hotfixLizyShell' : `git checkout Hotfix-4-release-lizy && git pull && git status  && git merge Hotfix-4-release  && git status && git push`,
		'lizyShell' : `git checkout Release && git pull  && git status && git merge Hotfix-4-release  && git status && git push`,
		// 通用模式
		'yuanzyShell' : `git checkout YUANZY-Release && git pull  && git status  && git merge Hotfix-4-release  && git status && git push`,
		'zywangShell' : `git checkout Release-OEM-zywang && git pull  && git status  && git merge Hotfix-4-release  && git status && git push`,
		'farcoachShell' : `git checkout FARCOACH-Release && git pull  && git status  && git merge Hotfix-4-release  && git status && git push`,
		'ddsxShell' : `git checkout Release-OEM-ddsx && git pull  && git status  && git merge Hotfix-4-release  && git status && git push`,
		'zwzytShell' : `git checkout Release-OEM-zwzyt && git pull  && git status  && git merge Hotfix-4-release  && git status && git push`,
		'bangzyShell' : `git checkout Release-OEM-bangzy && git pull  && git status  && git merge Hotfix-4-release  && git status && git push`,
		'dingzyShell' : `git checkout Release-OEM-dingzy && git pull  && git status  && git merge Hotfix-4-release  && git status && git push`,
		'yuanzyaiShell' : `git checkout Release-OEM-yuanzyai && git pull  && git status  && git merge Hotfix-4-release  && git status && git push`,
		'honghuaShell' : `git checkout Release-OEM-honghua && git pull  && git status  && git merge Hotfix-4-release  && git status && git push`,
	}
	let arr = env.includes(',') ? env.split(',') : env.split(' ');
	if(arr.length > 1) {
		for(let key of arr) {
			cmd += shellOpts[key+'Shell'] + ' && ';
		}
		cmd = cmd.slice(0, cmd.length-3)
	} else {
		cmd += shellOpts[arr[0]+'Shell'];
	}
	console.log('**************** cmd ********************')
	console.log(env,arr)
	console.log(cmd)
	console.log('**************** cmd end ****************')
	return run(cmd).exec()
}
// html文档处理
function htmlfile(){
	let path = `dist/new3.html`;
	console.log('plus', plus , _mp[env])
	return src('dist/new3.html').pipe(replace(/style\s*?=\s*?(['"])[\s\S]*?\1/g, function(match,p1,offset,string){
		let str = match.slice(0, match.indexOf("'"))
		return '';
	}))
	.pipe(dest('dist/file'))
}

//小程序编译
function mpCli() {
	// let cmd = `cd D:/HBuilderX && cd && cli ver && `;
	// 添加Hbuilder环境变量
	let cmd = `cli ver && `;
	// cli publish --platform mp-weixin --project 项目名称 --upload true --appid 小程序appid --description 发布描述 --version 发布版本 --privatekey 小程序上传密钥文件  --robot 2
	let shellOpts = {
		// 立志愿 通用模式
		'lizyShell' : `cli publish --platform MP-WEIXIN --project gaokao-mp --name 立志愿`,
	}
	cmd += shellOpts.lizyShell
	// let arr = env.includes(',') ? env.split(',') : env.split(' ');
	// if(arr.length > 1) {
	// 	for(let key of arr) {
	// 		cmd += shellOpts[key+'Shell'] + ' && ';
	// 	}
	// 	cmd = cmd.slice(0, cmd.length-3)
	// } else {
	// 	cmd += shellOpts[arr[0]+'Shell'];
	// }
	console.log('**************** cmd ********************')
	// console.log(env,arr)
	console.log(cmd)
	console.log('**************** cmd end ****************')
	return run(cmd).exec()
}

exports.run = shellRun;
exports.file = series(parallel([jsonConvert, fileLoad]), shellRun, mpCli);
exports.fileTest = series(parallel([jsonConvertTest, fileLoadTest]), shellRun);
exports.gaokaoWeb = gaokaoWebMerge
exports.gaokaoMp = gaokaoMpMerge
exports.jsons = jsonConvert;
exports.title = setTitle;
exports.fav = favicon;
exports.fileName = parallel([fileName,moveFile]);
exports.qr = getVipEncode;
exports.htmlfile = htmlfile;
exports.mpcli = mpCli
exports.default = function () {
	// watch(staticPath + "css/*.b.scss", series(css));
	console.log('_mp', _mp)
	return;
};
